﻿/*
 * Creato da SharpDevelop.
 * Utente: Ciccio
 * Data: 25/12/2008
 * Ora: 12.39
 * 
 */

using System;
using System.Data;
using System.Xml;
using System.IO;
using System.Web;
using Newtonsoft.Json;

	/// <summary>
	/// Description of HandlerGMenu.
	/// </summary>
	public class gMenu_Op2 : System.Web.UI.Page
	{

		void PrintResponse(string message, bool success) {
			Response.ContentType = "text/xml";
			Response.Clear();
			Response.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
			Response.Write( (success?"<done>":"<error>") + message + (success?"</done>":"</error>") );
			return;
		}		
		
		void Page_Load(object o, EventArgs e ) {
			string mode = Request.QueryString["mode"];
//			mode="savemenuforgroup";
			if(string.IsNullOrEmpty(mode)) {
				PrintResponse("No Mode",false);
				return;
			}
			mode = mode.Trim().ToLower();
			try {
			switch(mode) {
					case "savemenuforgroup":
						Elabora(); //PrintResponse("OK,inizio as leggere if dati",false);
						break;
					case "clearmenuforgroup":		
						ElaboraReset(); //PrintResponse("OK,inizio as leggere if dati",false);
						break;						
					default:
						PrintResponse("Funzione non riconosciuta",false);
						break;
			}
			} catch (Exception ex) {
				PrintResponse("ERRORE: "+ ex.ToString().Replace("'","\\'"),false);
			}
			return;
		}
		void ElaboraReset() {
			string role = Request.Form["role"];
			if(string.IsNullOrEmpty(role)) {
				PrintResponse("No role",false);
				return;
			}
			string _remove="delete from "+ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + "usermenu where rolename='{0}' ;";
			int reso = ACM.cmsarea08.DBManager.mainConnection.Helper_NonQuery(string.Format(_remove,role));
			if(reso>0)
				PrintResponse("OK:" + (reso) ,true);
			else
				PrintResponse("FALSE" ,false);
		}
		
		void Elabora() {
			string role = Request.Form["role"];
			string depending = Request.Form["depending"];
			string score = Request.Form["score"];
			string security = Request.Form["security"];
			string lang = Request.Form["lang"];
			string data = Request.Form["data"];
			if(string.IsNullOrEmpty(role)) {
				PrintResponse("No role",false);
				return;
			}
			if(string.IsNullOrEmpty(score)) {
				PrintResponse("No score",false);
				return;
			}	
			if(string.IsNullOrEmpty(security)) {
				PrintResponse("No security",false);
				return;
			}			
			if(string.IsNullOrEmpty(data)) {
				PrintResponse("No data",false);
				return;
			}		
			//se depending null string.empty:
			if(string.IsNullOrEmpty(depending)) depending = string.Empty;
			if(string.IsNullOrEmpty(lang)) lang = ACM.cmsarea08.mainconfiguration.MainConf.LinguaPredefinita;
			Newtonsoft.Json.Linq.JObject[] oggetti = new Newtonsoft.Json.Linq.JObject[0];
			oggetti = getMenu(data.Trim());
			string insert="insert into "+ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + "usermenu " +
				"(rolename,menu_id,parent_xpath,original_xpath,dataxml) " +
				"VALUES(" +
				"'{0}','{1}','{2}','{3}','{4}');\n\n";
			
			string _remove="delete from "+ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + "usermenu where rolename='{0}' ;";
			string qq = "";
			for(int i = 0 ;i<oggetti.Length;i++) {
				string menu="";
				string parent="";
				string o_parent="";
				string xmld  = "";
				if(oggetti[i]["menu_id"]!=null) menu=oggetti[i]["menu_id"].ToString();
				if(oggetti[i]["parent_xpath"]!=null) parent=oggetti[i]["parent_xpath"].ToString();
				if(oggetti[i]["xmlData"]!=null) xmld=oggetti[i]["xmlData"].ToString();
				if(oggetti[i]["original_xpath"]!=null) o_parent=oggetti[i]["original_xpath"].ToString();
				if(string.IsNullOrEmpty(menu)  ) continue;
				if(string.IsNullOrEmpty(parent)) continue;
				if(menu.StartsWith("\"")) menu = menu.Substring(1);
				if(menu.EndsWith("\"")) menu = menu.Substring(0,menu.Length-1);
				if(parent.StartsWith("\"")) parent = parent.Substring(1);
				if(parent.EndsWith("\"")) parent = parent.Substring(0,parent.Length-1);
				if(o_parent.StartsWith("\"")) o_parent = o_parent.Substring(1);
				if(o_parent.EndsWith("\"")) o_parent = o_parent.Substring(0,o_parent.Length-1);		
				if(xmld.StartsWith("\"")) xmld = xmld.Substring(1);
				if(xmld.EndsWith("\"")) xmld = xmld.Substring(0,xmld.Length-1);
				if(o_parent.ToLower()=="null")o_parent="";
				string ins=string.Format(insert,
				                         ACM.cmsarea08.Function.TextClass.textclass.SqlTesto(role),
				                         ACM.cmsarea08.Function.TextClass.textclass.SqlTesto(menu),
				                         ACM.cmsarea08.Function.TextClass.textclass.SqlTesto(parent),
				                         ACM.cmsarea08.Function.TextClass.textclass.SqlTesto(o_parent),
				                         ACM.cmsarea08.Function.TextClass.textclass.SqlTesto(xmld,false)
				                        );
				qq+=ins;
			}

				
			ACM.cmsarea08.DBManager.mainConnection.Helper_NonQuery(string.Format(_remove,role));
			int reso = ACM.cmsarea08.DBManager.mainConnection.Helper_NonQuery(qq);
			if(reso>0)
				PrintResponse("OK:" + (reso) ,true);
			else
				PrintResponse("FALSE:" + (qq) ,false);
		}
		
		
		private Newtonsoft.Json.Linq.JObject[] getMenu(string data) {
			string valori = data;
			if(valori == string.Empty) {
				return new Newtonsoft.Json.Linq.JObject[0];	
			}
			if(valori.StartsWith("[") )
				valori = valori.Substring(1);
			if(valori.EndsWith("]"))
				valori = valori.Substring(0,valori.Length-1);
			string[] valorA = new string[0];
			valorA = System.Text.RegularExpressions.Regex.Split(valori,"},{");
			//object[] jasone = new object[valorA.Length];
			//string finalXML = "";
			Newtonsoft.Json.Linq.JObject[] oggetto=new Newtonsoft.Json.Linq.JObject[valorA.Length];
			
			for(int i = 0; i<valorA.Length; i ++) {
				if(i==0)
					valorA[i] = valorA[i] + "}";
				else if(i==valorA.Length-1)
					valorA[i] = "{" + valorA[i] ;
				else
					valorA[i] = "{" + valorA[i] + "}";					
				valorA[i] = valorA[i].Replace("\n\r","");
				valorA[i] = valorA[i].Replace("\n","");
				valorA[i] = valorA[i].Replace("\r","");
				try { 
					try {
						oggetto[i] = Newtonsoft.Json.Linq.JObject.Parse( valorA[i] );
					} catch (Exception exo) {
						oggetto[i]=null;
						continue;
					}/*
					if(oggetto!=null) {
						string itemo = "";	
						object _menu = oggetto["menu_id"];
						object _parent = oggetto["parent_xpath"];
						object _oriparent = oggetto["original_xpath"];
						object _dat = oggetto["xmlData"];
						itemo = 
							"<menu>" + _menu+"</menu>" +
							"<parent>" + _parent + "</parent>" +
							"<oparent>" + _oriparent + "</oparent>" +
							"<data><![CDATA[" + _dat + "]]></data>";
						itemo = "<item>" + itemo + "</item>";	
						finalXML+=itemo;
					}
					*/
				} catch (Exception ex) {
					HttpContext.Current.Response.Write("\nFINLER: " + ex + "# ");
					oggetto[i]=null;
					continue;
				}
			}
			//finalXML= "<elementi>" + finalXML + "</elementi>";
			return oggetto;
		}
	
		
	}
